{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "889f1070",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F\n",
    "#1. 创建 Query、Key 和 Value 张量\n",
    "q = torch.randn(2, 3, 4) # 形状 (batch_size, seq_len1, feature_dim)\n",
    "k = torch.randn(2, 4, 4) # 形状 (batch_size, seq_len2, feature_dim)\n",
    "v = torch.randn(2, 4, 4) # 形状 (batch_size, seq_len2, feature_dim)\n",
    "# 2. 计算点积，得到原始权重，形状为 (batch_size, seq_len1, seq_len2)\n",
    "raw_weights = torch.bmm(q, k.transpose(1, 2))\n",
    "# 3. 将原始权重进行缩放（可选），形状仍为 (batch_size, seq_len1, seq_len2)\n",
    "scaling_factor = q.size(-1) ** 0.5\n",
    "scaled_weights = raw_weights / scaling_factor\n",
    "# 4. 应用 softmax 函数，使结果的值在 0 和 1 之间，且每一行的和为 1\n",
    "attn_weights = F.softmax(scaled_weights, dim=-1) # 形状仍为 (batch_size, seq_len1, seq_len2)\n",
    "# 5. 与 Value 相乘，得到注意力分布的加权和 , 形状为 (batch_size, seq_len1, feature_dim)\n",
    "attn_output = torch.bmm(attn_weights, v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "10067227",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[-0.5476,  0.1485,  0.0807, -0.2692],\n",
       "         [-0.5118, -0.1278, -0.1846, -0.9184],\n",
       "         [-0.4600, -0.0676, -0.1448, -0.7520]],\n",
       "\n",
       "        [[-0.8415,  0.8045,  1.5253,  0.4558],\n",
       "         [-0.4667,  0.6294,  0.8493,  0.4709],\n",
       "         [-0.1052,  0.5399, -0.1296,  0.5918]]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "attn_output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c60484d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
